package com.yifeixi.validation.util;

import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import javax.validation.groups.Default;

/**
 * 手动校验工具类
 *
 * @author YiFeiXi
 */
public class ValidateUtil {

  private ValidateUtil() {
  }

  /**
   * 调用JSR-303的 validate 方法, 验证失败时抛出 ConstraintViolationException, 而不是返回constraintViolations 结果集.
   */
  public static void validate(Validator validator, Object object, Class<?>... groups) {
    Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
    if (!constraintViolations.isEmpty()) {
      throw new ConstraintViolationException(constraintViolations);
    }
  }

  public static void validate(Validator validator, Object object) {
    validate(validator, object, Default.class);
  }

}
